/**
 * 
 */
package com.massyframework.beanskin.launcher.scanning.maven;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * {@link XmlParser}, xml文件解析
 * @author huangkh
 *
 */
class XmlParser {

	/**
	 * 
	 */
	public XmlParser() {
		
	}
	
	/**
	 * 加载配置文件
	 * @param xml {@link File}
	 * @return {@link Document}
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	protected Document loadDocument(File xml) 
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(xml);
	}
	
	/**
	 * 获取{@code tagName}的节点的子节点。
	 * <p>
	 * 本方法仅适用于标签在整个文档内最多仅有一个的情景
	 * @param doc {@link Document},文档
	 * @param tagName {@link String},标签名称
	 * @return {@link NodeList}
	 */
	protected NodeList getChildNodesByTagNames(Document doc, String tagName) {
		NodeList result = doc.getElementsByTagName(tagName);
		
		if (result == null) return null;
		if (result.getLength() == 1) {
			return result.item(0).getChildNodes();
		}
		return null;
	}
	
	/**
	 * 获取节点数据
	 * @param node {@link Node}
	 * @return {@link String}
	 */
	protected String getTextContent(Node node) {
		return node == null ? null : node.getTextContent();
	}

}
